#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2018 crane <crane@his-pc>
#
# Distributed under terms of the MIT license.

"""

"""

import functools


def cmp_literal(l1, l2):
    # 31 > 123
    # 311 < 31  (可组成31311)
    # 313 == 31 (最后一位 3 == 3)
    # 314 > 31  (最后一位4 > 3)
    # 31-40 > 31  (40 > 31)
    # 31-30 < 31  (30 < 31)
    # 31-31-0 > 31  (30 < 31)

    len1 = len(l1)
    len2 = len(l2)

    # 长的在前面
    # long, short = l1, l2
    # if len1 < len2:
    #     long, short = l2, l1
    short = min(len1, len2)
    if l1[:short] > l2[:short]:
        return 1
    if l1[:short] < l2[:short]:
        return -1
    # long = max(len1, len2)

    # for i in range(short):
    #     if l1[i] > l2[i]:
    #         # return True
    #         return 1

    #     if l1[i] < l2[i]:
    #         return -1

    if len1 == len2:
        return 0

    if len1 > len2:
        return cmp_literal(l1[len2:], l2)
    else:
        return cmp_literal(l1, l2[len1:])


class Solution:
    """
    @param nums: A list of non negative integers
    @return: A string
    """
    def largestNumber(self, nums):
        # write your code here
        list_nums = [self.split_num_to_list(i) for i in nums]

        key = functools.cmp_to_key(cmp_literal)
        sorted_list_nums = sorted(list_nums, key=key, reverse=True)     # 从大到小排序

        # NOTE: 去掉sorted_list_nums开头的0

        # print(sorted_list_nums)
        # for i in range(0, len(nums)-1):
        #     if sorted_list_nums[i] == [0]:
        if sorted_list_nums[0] == [0]:      # 如果第一个元素为0, 后面都是0(从大到小排序)
            return "0"

        str_list = [self.num_list_to_str(num_list) for num_list in sorted_list_nums]
        return "".join(str_list)

    def num_list_to_str(self, num_list):
        # [1,2,3] ------> "123"
        return "".join([str(i) for i in num_list])

    def split_num_to_list(self, num):
        if num == 0:
            return [0]

        ret = []

        while num:
            ret.insert(0, num % 10)
            num = num // 10      # num //= 10

        return ret


def main():
    print("start main")
    s = Solution()
    ret = s.largestNumber([21, 211])
    print(ret)
    # ret = s.split_num_to_list(0)
    # print(ret)

    # ret = cmp_literal([2, 1], [2, 1, 2, 1, 2, 1])
    # print(ret)

if __name__ == "__main__":
    main()
